import webbrowser
import gtk
import gobject
from gettext import gettext as _

from option import Option
import helpers
import signals
import mode
import timer
import backend
import session
import prefs
import stats

class MainWindow:
	def __init__(self):
		self.xml = helpers.loadGlade('main.glade')
		self.window = self.xml.get_widget('MainWindow')
		self.tabs = self.xml.get_widget('NtbkTabs')

		self.stats = self.xml.get_widget('StatsNotebook')

		self.preinspection = self.xml.get_widget('SpinPreinspection')
		self.header = self.xml.get_widget('LabHeader')
		self.stackmat = self.xml.get_widget('CheckStackmat')

		self.scores = self.xml.get_widget('ScoreViewer')
		self.side = self.xml.get_widget('SidePanel')
		self.logs = self.xml.get_widget('StatusPanel')
		
		self.menuMode = self.xml.get_widget('MenuMode')
		self.menuTools = gtk.Menu()
		self.xml.get_widget('MenuTools').set_submenu(self.menuTools);

		self.sideText = []
		self.lastScore = 0
		self.lastLog = 0
		
		self.preinspection.set_value(int(Option().config.get('general.default_preinspection',0)))
		self.stackmat.set_active(bool(int(Option().config.get('general.stackmat', 0))))
		self.on_CheckStackmat_toggled(self.stackmat)
		
		self.initScores()
		self.initLogs()
	
		self.xml.signal_autoconnect(self)

		signals.emit('main.init')


	def initScores(self):
		""" Initalization routines for score viewer"""

		list = gtk.ListStore(int,str)
		self.scores.set_model(list)
		idCol = gtk.TreeViewColumn('#')
		scoreCol = gtk.TreeViewColumn('Score')

		self.scores.append_column(idCol)
		self.scores.append_column(scoreCol)

		idCell = gtk.CellRendererText()
		idCol.pack_start(idCell, True)
		idCol.add_attribute(idCell, 'text',0)
		idCol.set_cell_data_func(idCell, self.formatCol,False)

		scoreCell = gtk.CellRendererText()
		scoreCol.pack_start(scoreCell, True)
		scoreCol.add_attribute(scoreCell, 'text',1)
		scoreCol.set_cell_data_func(scoreCell, self.formatCol,True)

		list.set_sort_column_id(0, gtk.SORT_DESCENDING)

	def initLogs(self):
		""" Initalization routines for logs viewer"""

		list = gtk.ListStore(int,str)
		self.logs.set_model(list)
		idCol = gtk.TreeViewColumn()
		logCol = gtk.TreeViewColumn()

		self.logs.append_column(idCol)
		self.logs.append_column(logCol)

		idCell = gtk.CellRendererText()
		idCol.pack_start(idCell, True)
		idCol.add_attribute(idCell, 'text',0)
		idCol.set_property('visible', False)

		logCell = gtk.CellRendererText()
		logCol.pack_start(logCell, True)
		logCol.add_attribute(logCell, 'text',1)
		logCell.set_property('ypad',0)

		list.set_sort_column_id(0, gtk.SORT_DESCENDING)


	def on_MainWindow_destroy(self, widget):
		if Option().twisted:
			from twisted.internet import reactor
			Option().tabNet.teardown()
			reactor.stop()
		else:
			gtk.main_quit()
	
	def refresh(self):
		txt=['CubeAssistant']
		for sid in self.sideText:
			arr=sid()
			txt.append('-- '+arr[0]+' --')
			txt.extend(arr[1])

		self.side.get_buffer().set_text(str.join('\n\n',txt))

		self.colorAvg = gtk.gdk.color_parse(Option().config.get('colors.best_average','#eef'))
		self.colorBest = gtk.gdk.color_parse(Option().config.get('colors.best','#efe'))
		self.colorBestEmph = gtk.gdk.color_parse(Option().config.get('colors.best_emphasis','#7f7'))
		self.colorWorst = gtk.gdk.color_parse(Option().config.get('colors.worst','#fee'))
		self.colorWorstEmph = gtk.gdk.color_parse(Option().config.get('colors.worst.emphasis','#f77'))

		self.scores.queue_draw()

	def addLog(self, text):
		self.lastLog += 1
		self.logs.get_model().append([self.lastLog, ' '+str(text)])
		gobject.timeout_add(20,_autoscroll, self.logs)

	def addScore(self, t):
		self.lastScore += 1
		self.scores.get_model().append([self.lastScore, t])
		gobject.timeout_add(20,_autoscroll, self.scores)

	def setScores(self, scores):
		mod = self.scores.get_model()
		self.scores.set_model(None)
		
		mod.clear()
		self.lastScore = 0
		for t in scores:
			self.lastScore += 1
			mod.append([self.lastScore, t])

		self.scores.set_model(mod)
		gobject.timeout_add(20,_autoscroll,self.scores)
	
	def formatCol(self, column, cell, model, iter,scorecol):
		option = Option().session.options()
		color = gtk.gdk.color_parse('#FFF')
		pos = int(model[iter][0])
		score = float(model[iter][1])
		
		if pos >= option.bestavg_start and pos <= option.bestavg_end:
			if score == option.best:
				color = self.colorBestEmph
			elif score == option.worst:
				color = self.colorWorstEmph
			else:
				color = self.colorAvg
		else:
			if score == option.best:
				color = self.colorBest
			elif score == option.worst:
				color = self.colorWorst

		if scorecol:
			if self.lastScore-12+1==pos:
				cell.set_property('markup',''.join(['<b>',helpers.fmt(score),'</b>']))
			else:
				cell.set_property('markup',helpers.fmt(score))
	
		color and cell.set_property('cell-background-gdk', color)

		return False

	def recreateModeMenu(self, selected):
		modemenu=gtk.Menu()
		first=None
		for mode in Option().modes:
			item=gtk.RadioMenuItem(label=mode)
			modemenu.append(item)
			if mode==selected:
				item.set_active(True)

			item.connect('activate',helpers.ChangeMode,mode)
			if first==None:
				first=item
			else:
				item.set_group(first)
			item.show()

		self.menuMode.set_submenu(modemenu)

	def on_MenuQuit_activate(self, widget):
		self.window.destroy()

	def on_MenuAbout_activate(self, widget):
		gtk.about_dialog_set_url_hook(self.on_MainAbout_url_hook)

		dlg = gtk.AboutDialog() #manual dialog construction due to flaw with website link when using libglade
		dlg.set_version(helpers.REV)
		dlg.set_name('Cube Assistant')
		dlg.set_license(open('LICENSE').read())
		dlg.set_authors(['Michal Hordecki'])
		dlg.set_website('http://cubeassistant.googlecode.com')
		dlg.set_comments(_('Making your cubing smooth.'))
		dlg.run()
		dlg.hide()

	def on_MainAbout_url_hook(self, widget, link):
		print (1,link)
		webbrowser.open_new(widget.get_website())

	def on_MenuNewSession_activate(self, widget):
		Option().session.teardown()
		Option().session=session.Session()
		self.refresh()

	def on_MenuSaveSession_activate(self, widget):
		chooser = gtk.FileChooserDialog(title=_('Save session'),action=gtk.FILE_CHOOSER_ACTION_SAVE,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_SAVE,gtk.RESPONSE_OK))
		ret=chooser.run()
		if ret==gtk.RESPONSE_ACCEPT or ret==gtk.RESPONSE_OK:
			Option().session.save(chooser.get_filename())
		chooser.hide()

	def on_MenuLoadSession_activate(self, widget):
		chooser = gtk.FileChooserDialog(title=_('Open session'),action=gtk.FILE_CHOOSER_ACTION_OPEN,
                                  buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL,gtk.STOCK_OPEN,gtk.RESPONSE_OK))
		ret=chooser.run()
		if ret==gtk.RESPONSE_ACCEPT or ret==gtk.RESPONSE_OK:
			Option().session.load(chooser.get_filename())

		chooser.hide()

	def on_MenuPreferences_activate(self, widget):
		if not "windowPreferences" in Option():
			Option().windowPreferences = prefs.PreferencesWindow()

		Option().windowPreferences.window.present()

	def on_ButDiscard_clicked(self, widget):
		if Option().time_pending:
			backend.prepare()

	def on_ButPenalty_clicked(self, widget):
		if Option().time_pending:
			backend.process_time(helpers.unfmt(self.header.get_text())+2.0)

	def on_ButGo_clicked(self, widget):
		if Option().time_pending:
			backend.process_time(helpers.unfmt(self.header.get_text()))
		else:
			if self.stackmat.get_active():
				timer.run(timer.MODE_STACKMAT)
			else:
				timer.run(timer.MODE_NORMAL,self.preinspection.get_value_as_int())

	def on_ButRefreshStats_clicked(self, widget):
		stats.refresh()
	
	def on_CheckStackmat_toggled(self, widget):
		if widget.get_active():
			self.preinspection.set_sensitive(False)
		else:
			self.preinspection.set_sensitive(True)


def _autoscroll(widg):
	widg.get_vadjustment().set_value(0)
	return False



